import logging


from django.db import DatabaseError
from django.core.exceptions import ObjectDoesNotExist
from rest_framework.views import exception_handler
from rest_framework.response import Response
from rest_framework import status
from redis import RedisError

logger = logging.getLogger('django')


def custom_exception_handler(exc, context):
    """
    自定义异常处理
    :param exc: 异常类实例对象
    :param context: 抛出异常的执行上下文[context: 程序运行当前一行代码时，由解析器内部能提供的各种环境信息）]
    :return: Response响应对象
    """
    # 调用drf框架原生的异常处理方法
    response = exception_handler(exc, context)

    if response is None:
        # 抛出异常时的视图类对象
        view = context['view']
        if isinstance(exc, DatabaseError):
            """如果发生了数据库相关异常"""
            # 数据库异常
            logger.error('mysql数据库异常！[%s] %s' % (view, exc))
            response = Response({'errmsg': '服务器内部错误！'}, status=status.HTTP_507_INSUFFICIENT_STORAGE)

        elif isinstance(exc, RedisError):
            # redis异常
            logger.error('redis数据库异常！[%s] %s' % (view, exc))
            response = Response({'errmsg': '服务器内部错误！'}, status=status.HTTP_507_INSUFFICIENT_STORAGE)

        elif isinstance(exc, ObjectDoesNotExist):
            response = Response({"errmsg": "当前模型对象不存在！"}, status=status.HTTP_404_NOT_FOUND)

    return response
